// -------------------------------------------------
// BlinKit - BlinKit Library
// -------------------------------------------------
//   File Name: scheduled_action_impl.cpp
// Description: ScheduledAction Class
//      Author: Ziming Li
//     Created: 2022-03-31
// -------------------------------------------------
// Copyright (C) 2022 MingYang Software Technology.
// -------------------------------------------------

#include "blinkit/blink/renderer/bindings/core/scheduled_action.h"

#include "blinkit/blink/renderer/core/dom/document.h"

namespace blink {

ScheduledAction::ScheduledAction(JSContext *ctx, JSValueConst thisVal, int argc, JSValueConst *argv)
    : m_ctx(ctx), m_thisVal(JS_DupValue(ctx, thisVal)), m_callback(JS_DupValue(ctx, argv[0]))
{
    for (int i = 2; i < argc; ++i)
        m_args.emplace_back(JS_DupValue(m_ctx, argv[i]));
}

ScheduledAction::~ScheduledAction(void)
{
    for (JSValue arg : m_args)
        JS_FreeValue(m_ctx, arg);
    JS_FreeValue(m_ctx, m_callback);
    JS_FreeValue(m_ctx, m_thisVal);
}

void ScheduledAction::execute(ExecutionContext *context)
{
    ASSERT(context->isDocument());
    if (JS_IsFunction(m_ctx, m_callback))
    {
        JSValue retVal = JS_Call(m_ctx, m_callback, m_thisVal, m_args.size(), m_args.data());
        ASSERT(!JS_IsException(retVal)); // BKTODO: Show exception information?
        JS_FreeValue(m_ctx, retVal);
    }
    else if (JS_IsString(m_callback))
    {
        ASSERT(false); // BKTODO:
    }
    else
    {
        ASSERT(false); // BKTODO:
    }
}

} // namespace blink
